package pyip.lib.javalearn;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class TTxx {

	public static void main(String[] args) throws IOException {
		List<String> list = new ArrayList<String>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\ip\\haitao\\amazon\\availableIp.txt"))));
			String line = null;
			while ((line = br.readLine()) != null) {
				list.add(line);
			}
		} finally {
			if (br != null) {
				br.close();
			}
		}

		int successCount = 0, failCount = 0, errorCount = 0, totalCount = 0;

		String url = "http://www.parcelforce.com/track-trace";
		for (String ip : list) {
			totalCount++;
			try {
				System.out.println("\n==================================================");
				System.out.println("connect through ip: " + ip);
				URL u = new URL(url);
				String[] ipArray = ip.split(":");
				Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(ipArray[0], Integer.parseInt(ipArray[1])));
				URLConnection conn = u.openConnection(proxy);
				conn.setConnectTimeout(30000);
				InputStream in = conn.getInputStream();
				String html = readText(in);
				if (html.contains("Track your parcel")) {
					System.out.println("success, ip: " + ip);
					successCount++;
				} else {
					System.out.println("fail, ip: " + ip + "\n" + html);
					failCount++;
				}
			} catch (Exception ex) {
				errorCount++;
				if (!ex.getMessage().equals("Connection refused: connect") && !ex.getMessage().equals("Connection timed out: connect")) {
					ex.printStackTrace();
				} else {
					System.out.println("error: " + ex.getMessage());
				}
			}
		}

		System.out.println("successCount " + successCount + ", failCount " + failCount + ", errorCount " + errorCount + ", totalCount " + totalCount);
	}

	private static String readText(InputStream in) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} finally {
			if (br != null) {
				br.close();
			}
			in.close();
		}
		return sb.toString();
	}

}
